package com.siruier.boss.ui.activity.user

import android.util.Base64
import android.view.View
import androidx.core.view.isVisible
import com.siruier.boss.api.core.launchUI
import com.siruier.boss.api.core.toData
import com.siruier.boss.api.mallApi
import com.siruier.boss.databinding.ActivitySuppleInfoBinding
import com.siruier.boss.ui.activity.commom.SignatureActivity
import com.siruier.boss.ui.api.ApiObserver
import com.siruier.boss.ui.base.BaseActivity
import com.siruier.boss.ui.ext.toastMessageLong
import com.siruier.boss.ui.ext.value
import com.siruier.boss.ui.helper.AppConfigHelper.loadConfig
import com.siruier.boss.ui.helper.InjectBundle
import com.siruier.boss.ui.tool.image.select.domain.ImageSelectBean
import com.siruier.boss.ui.tool.image.select.imageSelect
import com.siruier.boss.ui.tool.image.select.service.intercept.ApiUploadFileIntercept
import com.siruier.boss.ui.utils.GlideUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import top.zibin.luban.Luban
import java.io.File

class SuppleInfoActivity : BaseActivity<ActivitySuppleInfoBinding>() {

    private val orderSn: String by InjectBundle()
    private var receiptImg: ImageSelectBean? = null
    private var phone: String? = null
    private var signatureFile: File? = null

    override fun initView() {
        loadConfig {
            vb.textReceiptContent.text = it.appReceiptContent
            vb.webView.loadUrl(it.appMobileAgreement)
        }
        bindViewClick(vb.tvSign, vb.ivSign, vb.ivReceipt, vb.buttonSubmit)
    }

    override fun onClick(v: View?) {
        when (v) {
            vb.tvSign, vb.ivSign -> launchStartActivityForResult(SignatureActivity::class.java) {
                signatureFile = it.data?.getSerializableExtra("signatureFile") as File
                GlideUtils.intoView(mThis, signatureFile, vb.ivSign)
                vb.tvSign.isVisible = false
                vb.ivSign.isVisible = true
            }
            vb.ivReceipt -> imageSelect.selectImage {
                isMultipleChoice = false
                onUploadSuccessListener = {
                    receiptImg = it?.get(0)
                    GlideUtils.intoView(mThis, receiptImg?.path, vb.ivReceipt)
                }
            }
            vb.buttonSubmit -> {
                if (signatureFile == null) {
                    "请先签名".toastMessageLong()
                    return
                }
                if (vb.etPhone.length() == 0) {
                    "请先输入手机号".toastMessageLong()
                    return
                }
                phone = vb.etPhone.value
                if (receiptImg == null) {
                    "请先选择回执照".toastMessageLong()
                    return
                }
                launchUI({
                    ApiUploadFileIntercept.uploadFile(
                        "idCard", mutableListOf(receiptImg)
                            .filterNotNullTo(mutableListOf())
                    )
                    val compressSignatureFile = withContext(Dispatchers.IO) {
                        Luban.with(mThis)
                            .load(signatureFile)
                            .get()[0]
                    }
                    mallApi.fillInfo(
                        orderSn, phone, receiptImg?.url,
                        Base64.encodeToString(compressSignatureFile?.readBytes(), Base64.DEFAULT)
                    ).toData()
                }, ApiObserver(mThis, cancelable = false) {
                    "提交成功等待审核".toastMessageLong()
                    finish()
                })
            }
        }
    }

    override fun initData() {
        launchUI({
            mallApi.fillInfoDetail(orderSn).toData()?.let {
                signatureFile = withContext(Dispatchers.IO) {
                    val dirFile = File(externalCacheDir, "sign")
                    if (!dirFile.exists()) {
                        dirFile.mkdirs()
                    }
                    File(dirFile, "orderSn_$orderSn.png").also { file ->
                        file.writeBytes(Base64.decode(it.sign, Base64.DEFAULT))
                    }
                }
                GlideUtils.intoView(mThis, signatureFile, vb.ivSign)

                phone = it.phone
                vb.etPhone.setText(it.phone)

                receiptImg = ImageSelectBean().apply {
                    url = it.receiptImg
                }
                GlideUtils.intoView(mThis, it.receiptImg, vb.ivReceipt)
            }
        }, ApiObserver())
    }
}